package com.subsequent.controller;

import com.subsequent.entity.Medicines;
import com.subsequent.service.MedicinesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/medicines")
public class MedicinesController {

    @Autowired
    private MedicinesService medicinesService;

    // 分页+条件查询
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) String medicineName,
            @RequestParam(required = false) String code,
            @RequestParam(required = false) Integer isPrescription,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        int offset = (pageNum - 1) * pageSize;
        List<Medicines> list = medicinesService.selectByCondition(medicineName,isPrescription, code, status, startTime, endTime);
        int total = medicinesService.countByCondition(medicineName,isPrescription, code, status, startTime, endTime);
        Map<String, Object> result = new HashMap<>();
        result.put("data", list.subList(Math.min(offset, list.size()), Math.min(offset + pageSize, list.size())));
        result.put("total", total);
        return result;
    }

    // 新增
    @PostMapping("/add")
    public String add(@RequestBody Medicines medicines) {
        medicinesService.insert(medicines);
        return "success";
    }

    // 编辑
    @PostMapping("/edit")
    public String edit(@RequestBody Medicines medicines) {
        medicinesService.update(medicines);
        return "success";
    }

    // 删除
    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        medicinesService.deleteById(id);
        return "success";
    }

    // 详情
    @GetMapping("/detail/{id}")
    public Medicines detail(@PathVariable("id") Integer id) {
        return medicinesService.selectById(id);
    }

}